<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>

    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<div class="row">
    <div class="col-12">
        <h3>
            hello socket
            <span style="margin-left: 10px; font-size: 14px; font-weight: normal;">
            <a class="default-btn" onclick="operateSocket(SOCKET_FUNC.OPEN())">开启socket</a>
        </span>
        </h3>
        <p>【userId】：<input id="userId" name="userId" type="text"/></p>
        <p>【目标】：<input id="toUserId" name="toUserId" type="text"/></p>
        <p>【内容】：
        <div>
            <textarea id="contentText" name="contentText" cols="50" rows="4"></textarea>
        </div>

        <p>【操作】：<a class="primary-btn" onclick="operateSocket(SOCKET_FUNC.SEND_MESSAGE())">发送消息</a></p>
        <p>【操作】：<a class="primary-btn" onclick="a1()">点击</a></p>
    </div>

    <div class="col-12">
        <h3>接收内容</h3>
        <div class="receiveMsg">
        </div>
    </div>
</div>
</body>
<script>
    function a1() {

        $.ajax(
            {
                url: "http://10.40.161.25:80/test/sendData",
                async: false,
                method: 'get',
                headers: {
                  "x-token": "abc"
                },
                success: function (data) {
                    console.info(data)
                }
            }
        );
    }

</script>
<script>


    const SOCKET_FUNC = {
        OPEN: openSocket,
        SEND_MESSAGE: sendMessage
    };

    function operateSocket(fn) {
        if (typeof(WebSocket) === "undefined") {
            console.log("您的浏览器不支持WebSocket");
        } else {
            if (fn && typeof(fn) === "function") {
                console.log("您的浏览器支持WebSocket");
                fn()
            }
        }
    }


    let socket;

    function openSocket() {
        //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
        let userId = uuid2(32);
        document.getElementById('userId').value = userId;
        let socketUrl = "wss://do.vip.com:16611/socket/" + userId;
        console.log(socketUrl);
        if (socket != null) {
            socket.close();
            socket = null;
        }
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function () {
            console.log("websocket已打开");
            //socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        //获得消息事件
        socket.onmessage = function (ws) {
            let data = ws.data;
            console.info(data);
            // 需要用fileReader读取二进制Blob
            let reader = new FileReader();
            reader.readAsText(data, 'uft-8');
            reader.onload = () =>{
                let result = reader.result;
                let serverMsg = "收到服务端信息：" + result;
                console.log(serverMsg);
                // 发现消息进入
                // 开始处理前端触发逻辑
                let receiveMsg = document.querySelector(".receiveMsg");
                let p = document.createElement("p");
                p.innerText = result;
                receiveMsg.appendChild(p)
            }

        };
        //关闭事件
        socket.onclose = function () {
            console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
            console.log("websocket发生了错误");
        }
    }

    function sendMessage() {
        if (typeof(WebSocket) === "undefined") {
            console.log("您的浏览器不支持WebSocket");
        } else {
            // console.log("您的浏览器支持WebSocket");
            let userId = document.getElementById('userId').value;
            let toUserId = document.getElementById('toUserId').value;
            let contentText = document.getElementById('contentText').value;
            let msg = {
                sendId: userId,
                toUserId: toUserId,
                contentText: contentText
            };
            msg = JSON.stringify(msg);
            // 发送ArrayBuffer二进制数据，后台需要用ByteBuffer接收
            let blob = new Blob([msg], {
                type: 'text/plain'
            });
            let reader = new FileReader();
            reader.readAsArrayBuffer(blob);
            reader.onload = function (e) {
                console.log(reader.result);
                socket.send(reader.result);
            }

        }
    }



    /**
     * 生成uuid
     * @param len
     * @param radix
     * @returns {string}
     */
    function uuid2(len, radix) {
        let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        let uuid = [],
            i;
        radix = radix || chars.length;

        if (len) {
            // Compact form
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
        } else {
            // rfc4122, version 4 form
            let r;

            // rfc4122 requires these characters
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';

            // Fill in random data.  At i==19 set the high bits of clock sequence as
            // per rfc4122, sec. 4.1.5
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }

        return uuid.join('');
    }

</script>
<style>
    .row {
        position: relative;
        box-sizing: border-box;
        margin-bottom: 20px;
    }

    .row:before {
        display: table;
    }

    .row:after {
        clear: both;
    }

    .col-1 {
        width: 100%;
    }

    .col-6 {
        width: 25%;
    }

    .col-8 {
        width: 33.33333%;
    }

    .col-12 {
        width: 50%;
    }

    [class*=col-] {
        float: left;
        box-sizing: border-box;
    }

    a {
        cursor: pointer;
    }

    .default-btn {
        padding: 5px 8px;
        border: 1px solid #aeaeae;
        border-radius: 4px;
        background-color: #fff;
        font-size: 14px;
    }

    .primary-btn {
        padding: 5px 8px;
        border: 1px solid #409eff;
        border-radius: 4px;
        background-color: #409eff;
        font-size: 14px;
        color: #fff;
    }
</style>
</html>